from lib.clock import rtc_clock, ticker_clock
from lib.sensors.ssd1306.oled import OLED
from machine import Timer
from lib.config.index import sensor_config
import framebuf
from lib.sensors import dht11
from utils import device

p0 = bytearray([0x18, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00])
fb0 = framebuf.FrameBuffer(p0, 8, 8, framebuf.MONO_HLSB)

# oled config
oled_config = sensor_config.get_sensor("ssd1306")
scl = oled_config["scl"]
sda = oled_config["sda"]
width = oled_config["width"]
height = oled_config["height"]

# dht config
dht_config = sensor_config.get_sensor("dht11")
dht_pin = dht_config["pin"]
temp = -1
humidity = -1
mcu_temp = -1

c_timer1 = ticker_clock.TickerClock(12 * 3600 * 1000)
tim0 = Timer(0)
tim1 = Timer(1)

_oled = OLED(scl, sda, width, height)


def show_dht11():
    global _oled, temp, humidity
    _oled.rect(0, 24, 128, 30, 0)
    y = 24
    _oled.text("t: " + str(temp), 0, y)
    _oled.blit(fb0, 45, y)
    _oled.text("C", 52, y)
    _oled.text("h: " + str(humidity) + "%", 72, y)
    _oled.show()


def show_time():
    global _oled
    # print(clock.get_date_str(),clock.get_time_str())
    _oled.rect(0, 0, 128, 20, 0)
    # print(clock.get_time_str())
    _oled.text(clock.get_date_str(), 0, 0)
    _oled.text(clock.get_time_str(), 0, 12)
    _oled.text("mcu:" + str(mcu_temp), 75, 12)
    _oled.show()


def get_dht11():
    global temp, humidity, mcu_temp
    (temp, humidity) = dht11.read_dht11(dht_pin)
    mcu_temp = device.get_temperature()


def show():
    show_time()
    show_dht11()

    # 同步时间
    if c_timer1.check():
        clock.sync_network_time()


if __name__ == "__main__":
    # time
    clock = rtc_clock.RTC_CLOCK()
    clock.sync_network_time()
    tim0.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: show())
    tim1.init(period=4000, mode=Timer.PERIODIC, callback=lambda t: get_dht11())
